"""
qes转html
"""

import os
import re
import shutil
qes_dir_path = "S:\epidata\\ccc"

def run_qes_convert_to_html(qes_dir_path):
  # 获取目录下的一个qes文件
  qes_file_name = next((f for f in os.listdir(qes_dir_path) if f.lower().endswith(".qes")),None)

  # 解析rec文件
  if qes_file_name is not None:
    qes_file_path = os.path.join(qes_dir_path, qes_file_name)
    
    # 读取文件
    qes_file = open(qes_file_path, 'r',encoding="gbk",errors='ignore') 
    form_data = ""
    all_dict_data = qes_file.readlines()
    # 处理每一行
    for line in all_dict_data:
      # 回车-br
      line = line.replace("\n","<br>")
      # 空格-nbsp
      line = line.replace(" ","&nbsp;")
      # 替换 }@#开头的数据为 } 及 替换 }@_开头的数据为}
      key_end_re = ['}@#*', '}@_*']
      for re_str in key_end_re:
        key_end = re.findall(re_str,line)
        key_end.sort(key=lambda x:len(x), reverse=True)   
        for key_end_str in key_end:
          line = line.replace(f"{key_end_str}","}")

      # 提取大括号内容，转换为input-name
      for input_name in re.findall(r'[\{](.*?)[}]',line):
        line = line.replace(f"{{{input_name}}}",f"<input name='{input_name}' value='{input_name}'>")
      
      form_data = f"{form_data}{line}\n"

    html_template_data = f"""<html><body><form>{form_data}
    </form></body></html>"""

    save_file_name = qes_file_name+".html"
    qes_new_path = os.path.join(qes_dir_path, save_file_name)
    with open(qes_new_path,"w",encoding='gb2312') as fs:
      fs.write(html_template_data)


    print("convert to html success!")
  else:
    print("file not fond")

if __name__ == '__main__':
  run_qes_convert_to_html(qes_dir_path)